import React, { ReactElement, useState, useEffect, useRef } from 'react'
import { Button, Input, Select } from 'antd'
import { getCategories, addArticles, getArticlesDetail, putArticlesDetail } from '@/api/article'
import { connect, history } from 'umi'
import { IArticleState } from '@/models/article'
import E from "wangeditor"
import styles from '../index.less'

const { Option } = Select;

interface Props {
    changeArticleInfo: Function,
    article: IArticleState
}

function Create({ changeArticleInfo, article }: Props): ReactElement {
    const [arr, setArr] = useState([])
    const [defaultValue, setDefaultValue] = useState([])
    const div = useRef()

    const id = history.location.pathname.split('/')[3]

    if (id) {
        useEffect(() => {
            const parent = history.location.state.parent
            getCategories().then(res => {
                const data = res.data.filter((item: any) => item._id === parent)[0].children
                setArr(data)
                getArticlesDetail(id).then(res => {
                    // title
                    changeArticleInfo('title', res.data.title)
                    setDefaultValue(res.data.cate)

                    // 初始化富文本编辑器
                    const editor = new E(div.current)

                    // 配置 onchange 回调函数
                    editor.config.onchange = function (newHtml: string) {
                        changeArticleInfo("content", newHtml)
                    };

                    editor.create()
                    editor.txt.html(res.data.content)
                })
            })
        }, [])

    } else {
        useEffect(() => {
            getCategories().then(res => {
                setArr(res.data[1].children)
            })

            // 初始化富文本编辑器
            const editor = new E(div.current)
            // 配置 onchange 回调函数
            editor.config.onchange = function (newHtml: string) {
                changeArticleInfo("content", newHtml)
            };

            editor.create()
        }, [])
    }

    function handleChange(value: any) {
        changeArticleInfo('cate', value)
    }

    function saveArticleInfo() {
        if (id) {
            putArticlesDetail(id, article).then(res => {
                history.push('/article/list')
            })
        } else {
            addArticles(article).then(res => {
                history.push('/article/list')
            })
        }
    }

    return (
        <div>
            <div className={styles.flex}>
                <span>
                    所属分类:
                </span>
                <div >
                    <Select
                        className={styles.w220}
                        mode="multiple"
                        // labelInValue
                        style={{ width: '100%' }}
                        placeholder="请选择分类"
                        defaultValue={defaultValue}
                        key={defaultValue}
                        onChange={handleChange}
                        optionLabelProp="label"
                    >
                        {
                            arr.map((item: any, index: number) => {
                                return <Option key={index} value={item._id} label={item.name}>
                                    <div className="demo-option-label-item">
                                        {item.name}
                                    </div>
                                </Option>
                            })
                        }


                    </Select>
                </div>
            </div>
            <div className={styles.flex}>
                <span>
                    标题:
                </span>
                <div>
                    {
                        id ? <Input value={article.title} onChange={(ev) => {
                            changeArticleInfo('title', ev.target.value)
                        }} /> : <Input onChange={(ev) => {
                            changeArticleInfo('title', ev.target.value)
                        }} />
                    }
                </div>
            </div>
            <div className={styles.flex}>
                <span>
                    内容:
                </span>
                <div style={{
                    zIndex: 1
                }}>
                    <div ref={div}></div>
                </div>
            </div>
            <div className={styles.flex}>
                <span>
                    <Button onClick={() => {
                        saveArticleInfo()
                    }}>保存</Button>
                </span>
            </div>
        </div>
    )
}

export default connect((state: any) => {
    const { article } = state
    return {
        article
    }
}, (dispatch) => {
    return {
        changeArticleInfo(classify: string, value: Array<string> | string) {
            dispatch({ type: "article/changeArticleInfo", classify, value })
        }
    }
})(Create)
